package club.looli.haoke.api.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import graphql.GraphQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * Created by looli on 2020/7/11
 * </p>
 *
 * <p>
 * graphql api 查询
 * </p>
 *
 * @author looli
 * @since 2020/7/11
 */
@RestController
@RequestMapping("graphql")
@CrossOrigin
public class GraphQLController {

    @Autowired
    private GraphQL graphQL;

    /**
     * query
     * @param query
     * @return
     * @throws IOException
     */
    @GetMapping
    public Map<String, Object> graphql(@RequestParam("query") String query) throws IOException {
        return this.graphQL.execute(query).toSpecification();
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @PostMapping
    public Map<String, Object> postGraphql(@RequestBody String json) throws IOException {
        JsonNode jsonNode = MAPPER.readTree(json);
        if(jsonNode.has("query")){
            String query = jsonNode.get("query").asText();
            return this.graphQL.execute(query).toSpecification();
        }
        return null;
    }
}
